import React, { useState, useEffect } from 'react';
import { useAuth } from '@hooks/AuthContext'; // 导入 useAuth 自定义 hook

// Hook for registering a new user
export function useRegister() {
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [isOk, setisOk] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const register = async (data) => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });
      setisOk(res.ok);
      const result = await res.json();
      setResponse(result);
    } catch (err) {
      setError(err);
    }
    setIsLoading(false);
  };


  return { register, response, error, isOk, isLoading };
}


export function useLogin() {
  const auth = useAuth();
  const [state, setState] = useState({
    response: null,
    error: null,
    isOk: false,
    isLoading: false,
  });

  const handleSuccess = (result) => {
    setState({
      response: result,
      error: null,
      isOk: true,
      isLoading: false,
    });
  };

  const handleError = (err) => {
    setState({
      response: null,
      error: err,
      isOk: false,
      isLoading: false,
    });
  };

  const login = async (data) => {
    setState((prevState) => ({ ...prevState, isLoading: true }));
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });
      const result = await res.json();
      if (res.ok) {
        handleSuccess(result);
        auth.login(result.result.user, result.result.access_token);
      } else {
        handleError(new Error(result.message || 'Login failed'));
      }
    } catch (err) {
      handleError(err);
    }
  };

  return { ...state, login };
}

// Hook for handling forgotten password
export function useForgotPassword() {
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const [isOk, setisOk] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const forgotPassword = async (data) => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/auth/forgot-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });
      setisOk(res.ok);
      const result = await res.json();
      setResponse(result);
    } catch (err) {
      setError(err);
    }
    setIsLoading(false);

  };

  return { forgotPassword, response, error, isOk, isLoading };
}

// Hook for getting user profile
export function useUserProfile() {
  const [profile, setProfile] = useState(null);
  const [error, setError] = useState(null);
  const [isOk, setisOk] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const getUserProfile = async (token) => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/users/', {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      setisOk(res.ok);
      const result = await res.json();
      setProfile(result);
    } catch (err) {
      setError(err);
    }
    setIsLoading(false);
  };

  return { getUserProfile, profile, error, isOk, isLoading };
}

// export function useTokenValidation() {
//     const [isValidToken, setIsValidToken] = useState(false);
//     const [isLoading, setIsLoading] = useState(true);
//     const [userInfo, setUserInfo] = useState(null);
//     const [isOk, setisOk] = useState(false);

//     useEffect(() => {
//         const token = localStorage.getItem('token');
//         if (!token) {
//             setIsLoading(false);
//             return;
//         }

//         async function validateToken() {
//             try {
//                 const response = await fetch('/api/users/', {
//                     method: 'GET',
//                     headers: {
//                         'Authorization': `Bearer ${token}`
//                     }
//                 });
//                 setisOk(response.ok);
//                 if (response.ok) {
//                     const data = await response.json();
//                     setUserInfo(data);
//                     setIsValidToken(true);
//                 } else {
//                     localStorage.setItem('token', "");
//                     setIsValidToken(false);
//                 }
//             } catch (error) {
//                 localStorage.setItem('token', "");
//                 setIsValidToken(false);
//             } finally {
//                 setIsLoading(false);
//             }
//         }
//         validateToken();
//     }, []);

//     return { isValidToken, isLoading, userInfo, isOk };
// }




